<template>
  <view class="page chat-box">
    <navBar1 back>{{ title }}</navBar1>

    <view class="chat-main-box" :style="{ height: chatMainHeight + 'px' }">
      <view class="chat-msg" @click="switchChatTabBox('none')" @touchstart="onTouchChat">
        <scroll-view class="scroll-box" scroll-y="true" upper-threshold="200" @scrolltoupper="onScrollToTop" @scrolltolower="onScrollToBottom" :scroll-into-view="'chat-item-' + scrollMsgIdx">
          <template v-if="chat && chat.messages">
            <view v-for="(msgInfo, idx) in showMessages" :key="showMinIdx + idx">
              <chat-message-item :ref="'message' + msgInfo.id" :active="showMinIdx + idx == activeMessageIdx" :headImage="headImage(msgInfo)" @call="onRtCall(msgInfo)" :showName="showName(msgInfo)" :quoteShowName="showName(msgInfo.quoteMessage)" @recall="onRecallMessage" @delete="onDeleteMessage" @copy="onCopyMessage" @quote="onQuoteMessage" @locateQuote="onLocateQuoteMessage" @longPressHead="onLongPressHead(msgInfo)" @download="onDownloadFile" @audioStateChange="onAudioStateChange" @top="onTopMessage" :id="'chat-item-' + (showMinIdx + idx)" :msgInfo="msgInfo">
              </chat-message-item>
            </view>
          </template>
        </scroll-view>
      </view>
      <view class="send-bar">
        <view v-if="!showRecord" class="iconfont icon-voice-circle" @click="onRecorderInput()"></view>
        <view v-else class="iconfont icon-keyboard" @click="onKeyboardInput()"></view>
        <chat-record v-if="showRecord" class="chat-record" @send="onSendRecord"></chat-record>
        <view v-else class="send-text">
          <editor id="editor" class="send-text-area" :placeholder="isReceipt ? '[回执消息]' : ''" :read-only="isReadOnly" @focus="onEditorFocus" @blur="onEditorBlur" @ready="onEditorReady" :adjust-position="false" @input="onTextInput">
          </editor>
          <view v-if="quoteMessage" class="quote-message">
            <view class="quote-text">{{ quoteMessageText }}</view>
            <uni-icons class="quote-remove" type="clear" size="20" color="#888" @click="onQuoteMessage(null)"></uni-icons>
          </view>
        </view>
        <view class="iconfont icon-icon_emoji" @click="onShowEmoChatTab()"></view>
        <view v-if="isEmpty" class="iconfont icon-add" @click="onShowToolsChatTab()">
        </view>
        <button v-if="!isEmpty" class="btn-send" type="primary" @touchend.prevent="sendTextMessage()" size="mini">
          发送
        </button>
      </view>
    </view>
    <view class="chat-tab-bar">
      <view v-if="chatTabBox == 'tools'" class="chat-tools" :style="{ height: keyboardHeight + 'px' }">
        <view class="chat-tools-item">
          <file-upload ref="fileUpload" :onBefore="onUploadFileBefore" :onSuccess="onUploadFileSuccess" :onError="onUploadFileFail">
            <view class="tool-icon iconfont icon-folder"></view>
          </file-upload>
          <view class="tool-name">文件</view>
        </view>
        <view class="chat-tools-item">
          <image-upload :maxCount="9" sourceType="album" :onBefore="onUploadImageBefore" :onSuccess="onUploadImageSuccess" :onError="onUploadImageFail">
            <view class="tool-icon iconfont icon-picture"></view>
          </image-upload>
          <view class="tool-name">相册</view>
        </view>
        <view class="chat-tools-item">
          <image-upload sourceType="camera" :onBefore="onUploadImageBefore" :onSuccess="onUploadImageSuccess" :onError="onUploadImageFail">
            <view class="tool-icon iconfont icon-camera"></view>
          </image-upload>
          <view class="tool-name">拍摄</view>
        </view>
        <view class="chat-tools-item">
          <video-upload :onBefore="onUploadVideoBefore" :onSuccess="onUploadVideoSuccess" :onError="onUploadVideoFail">
            <view class="tool-icon iconfont icon-film"></view>
          </video-upload>
          <view class="tool-name">视频</view>
        </view>
        <view class="chat-tools-item" @click="onRecorderInput()">
          <view class="tool-icon iconfont icon-microphone"></view>
          <view class="tool-name">语音消息</view>
        </view>
        <!-- #ifndef MP-WEIXIN -->
        <!-- 音视频不支持小程序 -->
        <view class="chat-tools-item" @click="onPriviteVideo()">
          <view class="tool-icon iconfont icon-video"></view>
          <view class="tool-name">视频通话</view>
        </view>
        <view class="chat-tools-item" @click="onPriviteVoice()">
          <view class="tool-icon iconfont icon-call"></view>
          <view class="tool-name">语音通话</view>
        </view>
        <!-- #endif -->
      </view>
      <scroll-view v-if="chatTabBox === 'emo'" class="chat-emotion" scroll-y="true" :style="{ height: keyboardHeight + 'px' }">
        <view class="emotion-item-list">
          <image class="emotion-item emoji-large" :title="emoText" :src="$emo.textToPath(emoText)" v-for="(emoText, i) in $emo.emoTextList" :key="i" @click="selectEmoji(emoText)" mode="aspectFit" lazy-load="true"></image>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import UNI_APP from "@/.env.js";
import navBar1 from "@/components/nav-bar/nav-bar1.vue";
import LZString from 'lz-string';
import * as wsApi from '@/common/wssocket';
export default {
  components: {
    navBar1,
  },
  data() {
    return {
      type: "",
      chatIdx: null,
      chat: {},
      userInfo: {},
      isReceipt: false, // 是否回执消息
      scrollMsgIdx: 0, // 滚动条定位为到哪条消息
      chatTabBox: "none",
      showRecord: false,
      chatMainHeight: 0, // 聊天窗口高度
      keyboardHeight: 290,
      windowHeight: 1000, // 窗口高度
      initHeight: 1000, // h5初始高度
      needScrollToBottom: false, // 需要滚动到底部 
      showMinIdx: 0, // 下标小于showMinIdx的消息不显示，否则可能很卡
      showMaxIdx: -1, // 下标大于showMaxIdx的消息不显示，否则可能很卡
      reqQueue: [], // 请求队列
      isSending: false, // 是否正在发送请求
      isShowKeyBoard: false, // 键盘是否正在弹起 
      editorCtx: null, // 编辑器上下文
      isEmpty: true, // 编辑器是否为空
      isFocus: false, // 编辑器是否焦点
      isReadOnly: false, // 编辑器是否只读
      playingAudio: null, // 当前正在播放的录音消息,
      quoteMessage: null, // 被引用的消息
      activeMessageIdx: -1, // 选中消息idx
    };
  },
  onLoad(options) {
    uni.setStorageSync("loginInfo", options);
    uni.setStorageSync("userId", options.userId);
    this.targetId = options.targetId;

    // 进入页面生产假数据
    this.chat = {
      targetId: options.targetId,
      type: 'PRIVATE',
      showName: '测试用户',
      headImage: 'https://img.yzcdn.cn/vant/ipad.png',
      lastContent: '',
      lastSendTime: new Date().getTime(),
      unreadCount: 0,
      messages: [],
      atMe: false,
      atAll: false,
      stored: false,
      lastTimeTip: null
    };

    // 等待初始化完成后再获取聊天数据
    getApp().$vm.init().then(() => {
      console.log('初始化完成，开始获取聊天数据');

      if (options.reconnectSocket === 'true' && !wsApi.isConnected()) {
        // console.log("检测到需要重连WebSocket");
        // 重新连接WebSocket
        getApp().$vm.reconnectWs();
      }

      // 等待WebSocket数据获取完成后再进行赋值
      this.waitForWebSocketData(options).then(() => {
        console.log('WebSocket数据获取完成，开始初始化聊天页面');

        // 等待WebSocket数据获取完成后再获取聊天数据
        this.chat = this.chatStore.findChatByTargetId(options.targetId);

        // 如果获取不到聊天数据，尝试通过targetId查找
        if (!this.chat && options.targetId) {
          this.chat = this.chatStore.findChatByTargetId(options.targetId);
        }

        // 如果仍然获取不到，尝试通过chatIdx查找
        if (!this.chat && options.chatIdx) {
          this.chat = this.chatStore.findChatByTargetId(options.chatIdx);
        }

        console.log('获取到的聊天数据:', this.chat);

        // 初始化聊天页面
        if (this.chat) {
          this.initChatPage();
          // 激活当前会话
          this.chatStore.activeChat(this.chat.targetId);
          this.setupPage();
        } else {
          console.warn('未找到聊天数据，可能需要从服务器加载');
          // 如果没有找到聊天数据，尝试从服务器加载
          this.chatIdx = options.chatIdx || options.targetId;
          this.initChatByChatIdx();
        }
      }).catch((err) => {
        console.error('等待WebSocket数据超时:', err);
        // 即使WebSocket数据获取超时，也尝试获取聊天数据
        this.chat = this.chatStore.findChatByTargetId(options.targetId);
        if (!this.chat && options.targetId) {
          this.chat = this.chatStore.findChatByTargetId(options.targetId);
        }
        if (!this.chat && options.chatIdx) {
          this.chat = this.chatStore.findChatByTargetId(options.chatIdx);
        }

        if (this.chat) {
          this.initChatPage();
          this.chatStore.activeChat(this.chat.targetId);
          this.setupPage();
        } else {
          this.chatIdx = options.chatIdx || options.targetId;
          this.initChatByChatIdx();
        }
      });
    }).catch((err) => {
      console.error('初始化失败:', err);
      // 即使初始化失败，也尝试获取聊天数据
      this.chat = this.chatStore.findChatByTargetId(options.targetId);
      if (!this.chat && options.targetId) {
        this.chat = this.chatStore.findChatByTargetId(options.targetId);
      }
      if (!this.chat && options.chatIdx) {
        this.chat = this.chatStore.findChatByTargetId(options.chatIdx);
      }

      if (this.chat) {
        this.initChatPage();
        this.chatStore.activeChat(this.chat.targetId);
        this.setupPage();
      } else {
        this.chatIdx = options.chatIdx || options.targetId;
        this.initChatByChatIdx();
      }
    });

    // 先调用 userStore 中的 loadUser 方法
    // this.userStore.loadUser().then(() => {
    //   console.log("用户信息加载成功:", this.userStore.userInfo);


    //   this.init()

    //   // 使用 chatStore 的方法来获取或创建聊天对象
    //   this.chatStore.openChat(originalData);

    //   // 通过 chatStore 的方法获取聊天对象
    //   this.chat = this.chatStore.findChatByTargetId(originalData.targetId);

    //   // 如果找不到聊天对象，创建一个基本的聊天对象
    //   if (!this.chat) {
    //     this.chat = {
    //       targetId: originalData.targetId,
    //       type: originalData.type || 'PRIVATE',
    //       showName: originalData.showName || '未知用户',
    //       headImage: originalData.headImage || '',
    //       lastContent: originalData.lastContent || '',
    //       lastSendTime: originalData.lastSendTime || new Date().getTime(),
    //       unreadCount: originalData.unreadCount || 0,
    //       messages: originalData.messages || [],
    //       atMe: false,
    //       atAll: false,
    //       stored: false,
    //     };
    //     // 将聊天对象添加到 store 中
    //     this.chatStore.openChat(this.chat);
    //     // 重新获取 store 中的对象
    //     this.chat = this.chatStore.findChatByTargetId(originalData.targetId);
    //   }

    //   // 聊天记录通过 WebSocket 消息获取，不需要 HTTP 接口

    //   this.initChatPage();
    //   // 激活当前会话
    //   this.chatStore.activeChat(originalData.targetId);
    //   // 复位回执消息
    //   this.isReceipt = false;
    //   // 清空引用消息
    //   this.quoteMessage = null;
    //   // 监听键盘高度
    //   this.listenKeyBoard();
    //   // 计算聊天窗口高度
    //   this.$nextTick(() => {
    //     this.windowHeight = uni.getSystemInfoSync().windowHeight;
    //     this.reCalChatMainHeight();
    //     // 兼容ios h5:禁止页面滚动
    //     // #ifdef H5
    //     this.initHeight = window.innerHeight;
    //     document.body.addEventListener(
    //       "touchmove",
    //       function (e) {
    //         e.preventDefault();
    //       }, { passive: false },
    //     );
    //     // #endif
    //   });

    //   // 如果当前聊天对象没有消息，可以触发 WebSocket 拉取离线消息
    //   if (!this.chat.messages || this.chat.messages.length === 0) {
    //     // 触发 WebSocket 重连或拉取离线消息
    //     uni.$emit('WS_RECONNECTED');
    //   }
    // })
  },
  methods: {
    // 初始化聊天
    init() {

      return new Promise((resolve, reject) => {
        // 确保用户信息已加载
        this.ensureUserInfoLoaded().then(() => {
          console.log("用户信息加载完成");

          // 确保聊天store已初始化
          this.ensureChatStoreInitialized().then(() => {
            console.log("聊天store初始化完成");
            resolve();
          }).catch((err) => {
            console.error("聊天store初始化失败:", err);
            // 即使聊天store初始化失败，也继续执行
            resolve();
          });
        }).catch((err) => {
          console.error("用户信息加载失败:", err);
          // 即使用户信息加载失败，也继续执行
          console.log("继续执行后续逻辑，不阻止页面初始化");

          // 确保聊天store已初始化
          this.ensureChatStoreInitialized().then(() => {
            console.log("聊天store初始化完成");
            resolve();
          }).catch((err) => {
            console.error("聊天store初始化失败:", err);
            // 即使聊天store初始化失败，也继续执行
            resolve();
          });
        });
      });
    },

    async onRecorderInput() {
      if (!(await this.$permission.micro())) {
        console.log("录音权限未获得");
        return;
      }
      this.showRecord = true;
      this.switchChatTabBox("none");
    },
    onKeyboardInput() {
      this.showRecord = false;
      this.switchChatTabBox("none");
    },
    onSendRecord(data) {
      // 检查是否被封禁
      if (this.isBanned) {
        this.showBannedTip();
        return;
      }
      let msgInfo = {
        content: JSON.stringify(data),
        type: this.$enums.MESSAGE_TYPE.AUDIO,
        receipt: this.isReceipt,
      };
      // 填充对方id
      this.fillTargetId(msgInfo, this.chat.targetId);
      this.sendMessageRequest(msgInfo).then((m) => {
        m.selfSend = true;
        this.chatStore.insertMessage(m, this.chat);
        // 确保 this.chat 引用 store 中的最新对象
        this.chat = this.chatStore.findChatByTargetId(this.chat.targetId);
        // 会话置顶
        this.moveChatToTop();
        // 滚动到底部
        this.scrollToBottom();
        this.isReceipt = false;
      });
    },
    onRtCall(msgInfo) {
      if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VOICE) {
        this.onPriviteVoice();
      } else if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VIDEO) {
        this.onPriviteVideo();
      }
    },
    onPriviteVideo() {
      if (!this.isFriend) {
        uni.showToast({
          title: "对方已不是您的好友，无法呼叫",
          icon: "none",
        });
        return;
      }
      // 检查是否被封禁
      if (this.isBanned) {
        this.showBannedTip();
        return;
      }
      const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
      uni.navigateTo({
        url: `/pages/chat/chat-private-video?mode=video&friend=${friendInfo}&isHost=true`,
      });
    },
    onPriviteVoice() {
      if (!this.isFriend) {
        uni.showToast({
          title: "对方已不是您的好友，无法呼叫",
          icon: "none",
        });
        return;
      }
      // 检查是否被封禁
      if (this.isBanned) {
        this.showBannedTip();
        return;
      }
      const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
      uni.navigateTo({
        url: `/pages/chat/chat-private-video?mode=voice&friend=${friendInfo}&isHost=true`,
      });
    },
    onGroupVideo() {
      // 检查是否被封禁
      if (this.isBanned) {
        this.showBannedTip();
        return;
      }
      this.$http({
        url: "/webrtc/group/info?groupId=" + this.group.id,
        method: "GET",
      }).then((rtcInfo) => {
        if (rtcInfo.isChating) {
          // 已在通话中，可以直接加入通话
          this.$refs.rtcJoin.open(rtcInfo);
        } else {
          // 邀请成员发起通话
          let ids = [this.mine.id];
          this.$refs.selBox.init(ids, ids, []);
          this.$refs.selBox.open();
        }
      });
    },
    onInviteOk(ids) {
      if (ids.length < 2) {
        return;
      }
      let users = [];
      ids.forEach((id) => {
        let m = this.groupMembers.find((m) => m.userId == id);
        // 只取部分字段,压缩url长度
        users.push({
          id: m.userId,
          nickName: m.showNickName,
          headImage: m.headImage,
          isCamera: false,
          isMicroPhone: true,
        });
      });
      const groupId = this.group.id;
      const inviterId = this.mine.id;
      const userInfos = encodeURIComponent(JSON.stringify(users));
      uni.navigateTo({
        url: `/pages/chat/chat-group-video?groupId=${groupId}&isHost=true
						&inviterId=${inviterId}&userInfos=${userInfos}`,
      });
    },
    moveChatToTop() {
      let chatIdx = this.chatStore.findChatIdx(this.chat);
      this.chatStore.moveTop(chatIdx);
    },
    switchReceipt() {
      this.isReceipt = !this.isReceipt;
    },
    openAtBox() {
      this.$refs.atBox.init(this.atUserIds);
      this.$refs.atBox.open();
    },
    onAtComplete(atUserIds) {
      this.atUserIds = atUserIds;
    },
    onLongPressHead(msgInfo) {
      if (
        !msgInfo.selfSend &&
        this.chat && this.chat.type == "GROUP" &&
        this.atUserIds.indexOf(msgInfo.sendId) < 0
      ) {
        this.atUserIds.push(msgInfo.sendId);
      }
    },
    onTouchChat() {
      this.activeMessageIdx = -1;
      this.lockScrollEvent = false;
    },
    headImage(msgInfo) {
      return msgInfo.selfSend ?
        this.mine.headImageThumb :
        this.chat.headImage;
    },
    showName(msgInfo) {
      if (!msgInfo) return "";
      return msgInfo.selfSend ? this.mine.nickName : this.chat.showName;
    },
    sendTextMessage() {

      console.log(this.chatStore.curChats);
      this.editorCtx.getContents({
        success: (e) => {
          // 清空编辑框数据
          this.editorCtx.clear();
          // 检查是否被封禁
          if (this.isBanned) {
            this.showBannedTip();
            return;
          }
          let sendText = "";
          e.delta.ops.forEach((op) => {
            if (op.insert.image) {
              // emo表情
              sendText += `#${op.attributes.alt};`;
            } else
              // 文字
              sendText += op.insert;
          });
          if (!sendText.trim()) {
            return uni.showToast({
              title: "不能发送空白信息",
              icon: "none",
            });
          }
          let receiptText = this.isReceipt ? "【回执消息】" : "";
          let msgInfo = {
            content: receiptText + this.html2Escape(sendText),
            receipt: this.isReceipt,
            type: 0,
          };
          if (this.quoteMessage) {
            msgInfo.quoteMessageId = this.quoteMessage.id;
          }
          // 清空回执标记、引用消息
          this.isReceipt = false;
          this.quoteMessage = null;
          // 填充对方id
          this.fillTargetId(msgInfo, this.chat.targetId);
          this.sendMessageRequest(msgInfo)
            .then((m) => {
              m.selfSend = true;
              console.log('发送消息成功，更新前 this.chat:', this.chat);
              this.chatStore.insertMessage(m, this.chat);
              // 确保 this.chat 引用 store 中的最新对象
              this.chat = this.chatStore.findChatByTargetId(this.chat.targetId);
              console.log('发送消息成功，更新后 this.chat:', this.chat);
              // 会话置顶
              this.moveChatToTop();
            })
            .finally(() => {
              // 滚动到底部
              this.scrollToBottom();
            });
        },
      });
      if (this.type == "card") {
        uni.reLaunch({
          url: "/pages/chat/chat-box?chatIdx=" + this.chatIdx,
        });
      }
    },
    createAtText() {
      let atText = "";
      this.atUserIds.forEach((id) => {
        if (id == -1) {
          atText += ` @全体成员`;
        } else {
          let member = this.groupMembers.find((m) => m.userId == id);
          if (member) {
            atText += ` @${member.showNickName}`;
          }
        }
      });
      return atText;
    },
    fillTargetId(msgInfo, targetId) {
      msgInfo.recvId = targetId;
    },
    scrollToBottom() {
      let size = this.messageSize;
      if (size > 0) {
        this.scrollToMsgIdx(size - 1);
      }
    },
    scrollToMsgIdx(idx) {
      // 如果scrollMsgIdx值没变化，滚动条不会移动
      if (idx == this.scrollMsgIdx && idx > 0) {
        this.$nextTick(() => {
          // 先滚动到上一条
          this.scrollMsgIdx = idx - 1;
          // 再滚动目标位置
          this.scrollToMsgIdx(idx);
        });
        return;
      }
      this.$nextTick(() => {
        this.scrollMsgIdx = idx;
      });
    },
    onShowEmoChatTab() {
      this.showRecord = false;
      this.switchChatTabBox("emo");
    },
    onShowToolsChatTab() {
      this.showRecord = false;
      this.switchChatTabBox("tools");
    },
    switchChatTabBox(chatTabBox) {
      this.chatTabBox = chatTabBox;
      this.reCalChatMainHeight();
      if (chatTabBox != "tools" && this.$refs.fileUpload) {
        this.$refs.fileUpload.hide();
      }
    },
    selectEmoji(emoText) {
      let path = this.$emo.textToPath(emoText);
      // 先把键盘禁用了，否则会重新弹出键盘
      this.isReadOnly = true;
      this.isEmpty = false;
      this.$nextTick(() => {
        this.editorCtx.insertImage({
          src: path,
          alt: emoText,
          extClass: "emoji-small",
          nowrap: true,
          complete: () => {
            this.isReadOnly = false;
            this.editorCtx.blur();
          },
        });
      });
    },
    onUploadImageBefore(file) {
      // 检查是否被封禁
      if (this.isBanned) {
        this.showBannedTip();
        return;
      }
      let data = {
        originUrl: file.path,
        thumbUrl: file.path,
      };
      let msgInfo = {
        id: 0,
        tmpId: this.generateId(),
        fileId: file.uid,
        sendId: this.mine.id,
        content: JSON.stringify(data),
        sendTime: new Date().getTime(),
        selfSend: true,
        type: this.$enums.MESSAGE_TYPE.IMAGE,
        readedCount: 0,
        loadStatus: "loading",
        status: this.$enums.MESSAGE_STATUS.UNSEND,
      };
      // 填充对方id
      this.fillTargetId(msgInfo, this.chat.targetId);
      // 插入消息
      this.chatStore.insertMessage(msgInfo, this.chat);
      // 会话置顶
      this.moveChatToTop();
      // 借助file对象保存
      file.msgInfo = msgInfo;
      file.chat = this.chat;
      // 滚到最低部
      this.scrollToBottom();
      return true;
    },
    onUploadImageSuccess(file, res) {
      let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
      msgInfo.content = JSON.stringify(res.data);
      msgInfo.receipt = this.isReceipt;
      this.sendMessageRequest(msgInfo).then((m) => {
        msgInfo.loadStatus = "ok";
        msgInfo.id = m.id;
        this.isReceipt = false;
        this.chatStore.insertMessage(msgInfo, file.chat);
        // 确保 this.chat 引用 store 中的最新对象
        this.chat = this.chatStore.findChatByTargetId(this.chat.targetId);
      });
    },
    onUploadImageFail(file, err) {
      let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
      msgInfo.loadStatus = "fail";
      this.chatStore.insertMessage(msgInfo, file.chat);
    },
    onUploadVideoBefore(file) {
      // 检查是否被封禁
      if (this.isBanned) {
        this.showBannedTip();
        return;
      }
      let data = {
        videoUrl: file.tempFilePath,
        coverUrl: "",
      };
      let msgInfo = {
        id: 0,
        tmpId: this.generateId(),
        fileId: file.uid,
        sendId: this.mine.id,
        content: JSON.stringify(data),
        sendTime: new Date().getTime(),
        selfSend: true,
        type: this.$enums.MESSAGE_TYPE.VIDEO,
        readedCount: 0,
        loadStatus: "loading",
        status: this.$enums.MESSAGE_STATUS.UNSEND,
      };
      // 填充对方id
      this.fillTargetId(msgInfo, this.chat.targetId);
      // 插入消息
      this.chatStore.insertMessage(msgInfo, this.chat);
      // 会话置顶
      this.moveChatToTop();
      // 借助file对象保存
      file.msgInfo = msgInfo;
      file.chat = this.chat;
      // 滚到最低部
      this.scrollToBottom();
      return true;
    },
    onUploadVideoSuccess(file, res) {
      let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
      msgInfo.content = JSON.stringify(res.data);
      msgInfo.receipt = this.isReceipt;
      this.sendMessageRequest(msgInfo).then((m) => {
        msgInfo.loadStatus = "ok";
        msgInfo.id = m.id;
        this.isReceipt = false;
        this.chatStore.insertMessage(msgInfo, file.chat);
        // 确保 this.chat 引用 store 中的最新对象
        this.chat = this.chatStore.findChatByTargetId(this.chat.targetId);
      });
    },
    onUploadVideoFail(file, err) {
      let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
      msgInfo.loadStatus = "fail";
      this.chatStore.insertMessage(msgInfo, file.chat);
    },
    onUploadFileBefore(file) {
      // 检查是否被封禁
      if (this.isBanned) {
        this.showBannedTip();
        return;
      }
      let data = {
        name: file.name,
        size: file.size,
        url: file.path,
      };
      let msgInfo = {
        id: 0,
        tmpId: this.generateId(),
        sendId: this.mine.id,
        content: JSON.stringify(data),
        sendTime: new Date().getTime(),
        selfSend: true,
        type: this.$enums.MESSAGE_TYPE.FILE,
        readedCount: 0,
        loadStatus: "loading",
        status: this.$enums.MESSAGE_STATUS.UNSEND,
      };
      // 填充对方id
      this.fillTargetId(msgInfo, this.chat.targetId);
      // 插入消息
      this.chatStore.insertMessage(msgInfo, this.chat);
      // 会话置顶
      this.moveChatToTop();
      // 借助file对象保存
      file.msgInfo = msgInfo;
      file.chat = this.chat;
      // 滚到最低部
      this.scrollToBottom();
      return true;
    },
    onUploadFileSuccess(file, res) {
      let data = {
        name: file.name,
        size: file.size,
        url: res.data,
      };
      let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
      msgInfo.content = JSON.stringify(data);
      msgInfo.receipt = this.isReceipt;
      this.sendMessageRequest(msgInfo).then((m) => {
        msgInfo.loadStatus = "ok";
        msgInfo.id = m.id;
        this.isReceipt = false;
        this.chatStore.insertMessage(msgInfo, file.chat);
      });
    },
    onUploadFileFail(file, res) {
      let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
      msgInfo.loadStatus = "fail";
      this.chatStore.insertMessage(msgInfo, file.chat);
    },
    onDeleteMessage(msgInfo) {
      uni.showModal({
        title: "删除消息",
        content: "确认删除消息?",
        success: (res) => {
          if (!res.cancel) {
            this.chatStore.deleteMessage(msgInfo, this.chat);
            uni.showToast({
              title: "删除成功",
              icon: "none",
            });
          }
        },
      });
    },
    onRecallMessage(msgInfo) {
      uni.showModal({
        title: "撤回消息",
        content: "确认撤回消息?",
        success: (res) => {
          if (!res.cancel && this.chat) {
            let url = `/message/${this.chat.type.toLowerCase()}/recall/${msgInfo.id}`;
            this.$http({
              url: url,
              method: "DELETE",
            }).then((m) => {
              m.selfSend = true;
              this.chatStore.recallMessage(m, this.chat);
            });
          }
        },
      });
    },
    onQuoteMessage(msgInfo) {
      this.quoteMessage = msgInfo;
      this.onKeyboardInput();
    },
    onTopMessage(msgInfo) {
      if (!msgInfo.id) {
        uni.showToast({
          title: "请等待该消息发送成功后操作",
          icon: "none",
        });
        return;
      }
      this.$http({
        url: `/group/setTopMessage/${msgInfo.groupId}?messageId=${msgInfo.id}`,
        method: "POST",
      }).then(() => { });
    },
    onCopyMessage(msgInfo) {
      uni.setClipboardData({
        data: msgInfo.content,
        success: () => {
          uni.showToast({ title: "复制成功" });
        },
        fail: () => {
          uni.showToast({ title: "复制失败", icon: "none" });
        },
      });
    },
    onLocateQuoteMessage(msgInfo) {
      this.locateMessage(msgInfo.quoteMessage);
    },
    locateMessage(msgInfo) {
      // 寻找消息位置
      const idx = this.findMessageIdx(msgInfo);
      if (idx < 0) {
        uni.showToast({
          title: "无法定位原消息",
          icon: "none",
        });
        return;
      }
      // 要定位到消息，首先要显示这条消息
      if (this.showMinIdx > idx) {
        this.showMinIdx = Math.min(this.showMinIdx, Math.max(idx - 5, 0));
        this.showMaxIdx = this.showMinIdx + 20;
      }
      // 滚动至引用消息，-2是将引用消息定位到第4行
      this.scrollToMsgIdx(Math.max(this.showMinIdx, idx - 3));
      // 高亮消息2秒,提醒用户
      this.activeMessageIdx = idx;
      // 锁定滚动事件,避免干扰
      this.lockScrollEvent = true;
      // 2s后自动恢复正常
      setTimeout(() => {
        this.activeMessageIdx = -1;
        this.lockScrollEvent = false;
      }, 2000);
    },
    findMessageIdx(msgInfo) {
      if (!this.chat || !this.chat.messages) {
        return -1;
      }
      for (let idx in this.chat.messages) {
        const message = this.chat.messages[idx];
        // 通过id判断
        if (msgInfo.id && message.id && message.id == msgInfo.id) {
          return idx;
        }
        // 正在发送中的消息可能没有id,只有tmpId
        if (msgInfo.tmpId && message.tmpId && message.tmpId == msgInfo.tmpId) {
          return idx;
        }
      }
      return -1;
    },
    onDownloadFile(msgInfo) {
      let url = JSON.parse(msgInfo.content).url;
      uni.downloadFile({
        url: url,
        success(res) {
          if (res.statusCode === 200) {
            var filePath = encodeURI(res.tempFilePath);
            uni.openDocument({
              filePath: filePath,
              showMenu: true,
            });
          }
        },
        fail(e) {
          uni.showToast({
            title: "文件下载失败",
            icon: "none",
          });
        },
      });
    },
    onScrollToTop() {
      if (this.lockScrollEvent || this.showMinIdx == 0) {
        return;
      }
      //  #ifndef H5
      // 防止滚动条定格在顶部，不能一直往上滚
      this.scrollToMsgIdx(this.showMinIdx);
      // #endif
      // 多展示20条信息
      this.showMinIdx = this.showMinIdx > 20 ? this.showMinIdx - 20 : 0;
    },
    onScrollToBottom(e) {
      if (this.lockScrollEvent || this.showMaxIdx < 0) {
        return;
      }
      // 多展示20条信息
      this.showMaxIdx += 20;
    },
    onShowMore() {
      uni.navigateTo({
        url: "/pages/common/user-info?id=" + this.userInfo.id,
      });
    },
    onTextInput(e) {
      this.isEmpty = e.detail.html == "<p><br></p>";
    },
    onEditorReady() {
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this);
        query
          .select("#editor")
          .context((res) => {
            this.editorCtx = res.context;
          })
          .exec();
      });
    },
    onEditorFocus(e) {
      this.isFocus = true;
      this.scrollToBottom();
      this.switchChatTabBox("none");
    },
    onEditorBlur(e) {
      this.isFocus = false;
    },
    onAudioStateChange(state, msgInfo) {
      const playingAudio = this.$refs["message" + msgInfo.id][0];
      if (state == "PLAYING" && playingAudio != this.playingAudio) {
        // 停止之前的录音
        this.playingAudio && this.playingAudio.stopPlayAudio();
        // 记录当前正在播放的消息
        this.playingAudio = playingAudio;
      }
    },
    resetShowMessages() {
      // 初始状态仅渲染最后20条数据
      const messageCount = this.messageSize || 0;
      this.showMinIdx = messageCount > 20 ? messageCount - 20 : 0;
      this.showMaxIdx = -1;
    },
    loadReaded(fid) {
      // 只有在用户信息已加载的情况下才调用接口
      if (!this.userStore.userInfo || !this.userStore.userInfo.id) {
        console.log("用户信息未加载，跳过 loadReaded 接口调用");
        return;
      }

      this.$http({
        url: `/message/private/maxReadedId?friendId=${fid}`,
        method: "get",
      }).then((id) => {
        this.chatStore.readedMessage({
          friendId: fid,
          maxId: id,
        });
      }).catch((err) => {
        console.error("loadReaded 接口调用失败:", err);
      });
    },
    readedMessage() {
      if (this.unreadCount == 0) {
        return;
      }

      // 只有在用户信息已加载的情况下才调用已读接口
      if (!this.userStore.userInfo || !this.userStore.userInfo.id) {
        console.log("用户信息未加载，跳过已读接口调用");
        return;
      }

      let url = `/message/private/readed?friendId=${this.chat.targetId}`;
      this.$http({
        url: url,
        method: "PUT",
      }).then(() => {
        this.chatStore.resetUnreadCount(this.chat);
        this.scrollToBottom();
      }).catch((err) => {
        console.error("已读接口调用失败:", err);
      });
    },
    loadGroup(groupId) {
      this.groupId = groupId;
      this.$http({
        url: `/group/find/${groupId}`,
        method: "GET",
      }).then((group) => {
        this.chatStore.updateChatFromGroup(group);
        this.groupStore.updateGroup(group);
      }).catch((err) => {
        console.error("获取群组信息失败:", err);
        // 创建默认群组信息
        const defaultGroup = {
          id: groupId,
          name: '群聊',
          headImage: '',
          ownerId: '',
          isBanned: false,
          isMuted: false
        };
        this.chatStore.updateChatFromGroup(defaultGroup);
        this.groupStore.updateGroup(defaultGroup);
      });

      this.$http({
        url: `/group/members/${groupId}`,
        method: "GET",
      }).then((groupMembers) => {
        this.groupMembers = groupMembers;
      }).catch((err) => {
        console.error("获取群成员信息失败:", err);
        this.groupMembers = [];
      });
    },

    updateFriendInfo() {
      if (this.isFriend) {
        // store的数据不能直接修改，深拷贝一份store的数据
        let friend = JSON.parse(JSON.stringify(this.friend));
        friend.headImage = this.userInfo.headImageThumb;
        friend.nickName = this.userInfo.nickName;
        friend.showNickName = friend.remarkNickName ?
          friend.remarkNickName :
          friend.nickName;
        // 更新好友列表中的昵称和头像
        this.friendStore.updateFriend(friend);
        // 更新会话中的头像和昵称
        this.chatStore.updateChatFromFriend(friend);
      } else {
        this.chatStore.updateChatFromUser(this.userInfo);
      }
    },
    loadFriend(friendId) {
      // 获取好友用户信息
      this.$http({
        url: `/user/find/${friendId}`,
        method: "GET",
      }).then((userInfo) => {
        this.userInfo = userInfo;
        this.updateFriendInfo();
      }).catch((err) => {
        console.error("获取好友信息失败:", err);
        // 创建默认用户信息
        this.userInfo = {
          id: friendId,
          nickName: '未知用户',
          headImageThumb: '',
          isBanned: false
        };
        this.updateFriendInfo();
      });
    },
    rpxTopx(rpx) {
      // rpx转换成rpx
      let info = uni.getSystemInfoSync();
      let px = (info.windowWidth * rpx) / 750;
      return Math.floor(rpx);
    },
    html2Escape(strHtml) {
      return strHtml.replace(/[<>&"]/g, function (c) {
        return {
          "<": "&lt;",
          ">": "&gt;",
          "&": "&amp;",
          '"': "&quot;",
        }[c];
      });
    },
    sendMessageRequest(msgInfo) {
      return new Promise((resolve, reject) => {
        // 请求入队列，防止请求"后发先至"，导致消息错序
        this.reqQueue.push({ msgInfo, resolve, reject });
        this.processReqQueue();
      });
    },
    processReqQueue() {
      if (this.reqQueue.length && !this.isSending) {
        this.isSending = true;
        const reqData = this.reqQueue.shift();
        this.$http({
          url: this.messageAction,
          method: "post",
          data: reqData.msgInfo,
        })
          .then((res) => {
            reqData.resolve(res);
          })
          .catch((e) => {
            reqData.reject(e);
          })
          .finally(() => {
            this.isSending = false;
            // 发送下一条请求
            this.processReqQueue();
          });
      }
    },
    reCalChatMainHeight() {
      setTimeout(() => {
        let h = this.windowHeight;
        // 减去标题栏高度
        h -= 50;
        // 减去键盘高度
        if (this.isShowKeyBoard || this.chatTabBox != "none") {
          console.log("减去键盘高度:", this.keyboardHeight);
          h -= this.keyboardHeight;
          this.scrollToBottom();
        }
        // #ifndef H5
        // h5需要减去状态栏高度
        h -= uni.getSystemInfoSync().statusBarHeight;
        // #endif
        this.chatMainHeight = h;
        // console.log("窗口高度:", this.chatMainHeight);
        if (this.isShowKeyBoard || this.chatTabBox != "none") {
          this.scrollToBottom();
        }
        // ios浏览器键盘把页面顶起后，页面长度不会变化，这里把页面拉到顶部适配一下
        // #ifdef H5
        if (uni.getSystemInfoSync().platform == "ios") {
          // 不同手机需要的延时时间不一致，采用分段延时的方式处理
          const delays = [50, 100, 500];
          delays.forEach((delay) => {
            setTimeout(() => {
              uni.pageScrollTo({
                scrollTop: 0,
                duration: 10,
              });
            }, delay);
          });
        }
        // #endif
      }, 30);
    },
    listenKeyBoard() {
      // #ifdef H5
      if (navigator.platform == "Win32" || navigator.platform == "MacIntel") {
        // 电脑端不需要弹出键盘
        // console.log("navigator.platform:", navigator.platform);
        return;
      }
      if (uni.getSystemInfoSync().platform == "ios") {
        // ios h5实现键盘监听
        window.addEventListener("focusin", this.focusInListener);
        window.addEventListener("focusout", this.focusOutListener);
        // 监听键盘高度，ios13以上开始支持
        if (window.visualViewport) {
          window.visualViewport.addEventListener("resize", this.resizeListener);
        }
      } else {
        // 安卓h5实现键盘监听
        window.addEventListener("resize", this.resizeListener);
      }
      // #endif
      // #ifndef H5
      // app实现键盘监听
      uni.onKeyboardHeightChange(this.keyBoardListener);
      // #endif
    },
    unListenKeyboard() {
      // #ifdef H5
      window.removeEventListener("resize", this.resizeListener);
      window.removeEventListener("focusin", this.focusInListener);
      window.removeEventListener("focusout", this.focusOutListener);
      // #endif
      // #ifndef H5
      uni.offKeyboardHeightChange(this.keyBoardListener);
      // #endif
    },
    keyBoardListener(res) {
      this.isShowKeyBoard = res.height > 0;
      if (this.isShowKeyBoard) {
        this.keyboardHeight = res.height; // 获取并保存键盘高度
      }
      this.reCalChatMainHeight();
    },
    resizeListener() {
      console.log("resize:", window.innerHeight);
      let keyboardHeight = this.initHeight - window.innerHeight;
      this.isShowKeyBoard = keyboardHeight > 150;
      if (this.isShowKeyBoard) {
        this.keyboardHeight = keyboardHeight;
      }
      this.reCalChatMainHeight();
    },
    focusInListener() {
      console.log("focusInListener");
      this.isShowKeyBoard = true;
      this.reCalChatMainHeight();
    },
    focusOutListener() {
      console.log("focusOutListener");
      this.isShowKeyBoard = false;
      this.reCalChatMainHeight();
    },
    showBannedTip() {
      let msgInfo = {
        tmpId: this.generateId(),
        sendId: this.mine.id,
        sendTime: new Date().getTime(),
        type: this.$enums.MESSAGE_TYPE.TIP_TEXT,
      };
      msgInfo.recvId = this.mine.id;
      msgInfo.content = "该用户已被管理员封禁,原因:" + this.userInfo.reason;
      this.chatStore.insertMessage(msgInfo, this.chat);
    },
    generateId() {
      // 生成临时id 
      return (
        String(new Date().getTime()) + String(Math.floor(Math.random() * 1000))
      );
    },
    // 处理WebSocket重连事件
    handleWebSocketReconnect() {
      console.log("聊天页面检测到WebSocket重连");
      // 静默刷新聊天数据，减少UI闪烁
      this.silentRefreshChatData();
    },

    // 静默刷新聊天数据，避免页面闪烁
    silentRefreshChatData() {
      // 记住当前的滚动位置和状态
      const currentScrollPos = this.scrollMsgIdx;

      // 保存当前显示的消息ID列表，用于比较
      const oldMessageIds = this.showMessages.map(msg => msg.id || msg.tmpId);

      // 重新获取最新的chat数据
      this.chat = this.chatStore.curChats.find(chat => chat.targetId == this.chatIdx);
      console.log('this.chatStore.curChats', this.chatStore.curChats);
      console.log(this.chat);

      // 如果找不到chat数据，直接返回
      if (!this.chat) {
        console.warn("未找到对应的聊天数据");
        return;
      }

      // 计算新消息的数量
      const oldSize = oldMessageIds.length;
      const newSize = this.chat.messages.length;
      const hasNewMessages = newSize > oldSize;

      if (hasNewMessages) {
        // 只在有新消息时才更新显示范围和滚动位置
        this.showMinIdx = Math.max(0, newSize - UNI_APP.MAX_MESSAGE_SIZE);
        this.showMaxIdx = newSize - 1;

        // 平滑滚动到底部，不要立即跳转
        this.$nextTick(() => {
          this.smoothScrollToBottom();
        });
      } else {
        // 如果没有新消息，保持原来的滚动位置
        this.$nextTick(() => {
          this.scrollMsgIdx = currentScrollPos;
        });
      }

      // 静默标记已读
      this.silentMarkChatReaded();
    },

    // 平滑滚动到底部
    smoothScrollToBottom() {
      // 使用动画效果滚动到底部
      let size = this.messageSize;
      if (size > 0) {
        this.scrollToMsgIdx(size - 1);
      }
    },

    // 静默标记已读（不触发UI更新）
    silentMarkChatReaded() {
      if (!this.chat || this.chat.unreadCount === 0) {
        return; // 没有未读消息，不需要操作
      }

      this.$http({
        url: `/message/private/readed?friendId=${this.chat.targetId}`,
        method: 'PUT'
      }).then(() => {
        this.chatStore.resetUnreadCount(this.chat);
      });
    },
    initChatPage() {
      // 确保chat对象存在且有效
      if (!this.chat || !this.chat.targetId) {
        console.error("chat对象未正确初始化");
        // 只有在使用chatIdx参数时才尝试重新初始化
        if (this.chatIdx && !this.chat.messages) {
          console.log("尝试重新初始化聊天页面");
          this.initChatByChatIdx();
          return;
        }
        uni.showToast({
          title: "聊天数据加载失败",
          icon: "none"
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
        return;
      }

      // 初始状态只显示20条消息
      this.resetShowMessages();
      // 消息已读
      this.readedMessage();
      console.log("初始化聊天页面:", this.chat);

      // 只有当chat对象中没有完整的用户信息时才加载
      if (!this.chat.showName || !this.chat.headImage) {
        this.loadFriend(this.chat.targetId);
      }

      // 只有在用户信息已加载的情况下才调用 loadReaded
      if (this.userStore.userInfo && this.userStore.userInfo.id) {
        this.loadReaded(this.chat.targetId);
      } else {
        console.log("用户信息未加载，跳过 loadReaded");
      }

      // 监听 WebSocket 重连
      uni.$on("WS_RECONNECTED", this.handleWebSocketReconnect);
    },
    initChatByChatIdx() {
      // 通过chatIdx参数打开聊天页面，并获取聊天记录
      console.log("开始初始化聊天页面，chatIdx:", this.chatIdx);

      // 确保聊天store已初始化
      this.ensureChatStoreInitialized().then(() => {
        // 首先尝试从store中查找现有的聊天数据
        let existingChat = this.chatStore.findChatByTargetId(this.chatIdx);

        if (existingChat) {
          // 如果store中已有该聊天数据，直接使用
          console.log("找到现有聊天数据:", existingChat);
          this.chat = existingChat;
          this.initChatPage();
          // 激活当前会话
          this.chatStore.activeChat(this.chatIdx);
          this.setupPage();
        } else {
          // 如果store中没有，需要从服务器获取
          console.log("未找到现有聊天数据，从服务器加载");
          this.loadChatFromServer();
        }
      }).catch((err) => {
        console.error("聊天store初始化失败:", err);
        // 即使store初始化失败，也尝试直接加载聊天数据
        this.loadChatFromServer();
      });
    },

    loadChatFromServer() {
      // 从服务器加载聊天数据
      console.log("开始从服务器加载聊天数据，chatIdx:", this.chatIdx);

      // 获取用户信息
      this.$http({
        url: `/user/find/${this.chatIdx}`,
        method: "GET",
      }).then((userInfo) => {
        console.log("找到用户信息，开始加载私聊:", userInfo);
        // 是私聊，获取私聊消息
        this.userInfo = userInfo;
        this.loadPrivateChat();
      }).catch((err) => {
        console.error("Failed to load chat info:", err);
        // 不要立即返回上一页，而是创建一个空的聊天对象
        console.log("未找到聊天对象，创建空聊天对象");
        this.createEmptyChat();
      });
    },

    createEmptyChat() {
      // 创建一个空的聊天对象，避免页面循环刷新
      const chatInfo = {
        targetId: this.chatIdx,
        type: 'PRIVATE', // 默认为私聊类型
        showName: '未知用户',
        headImage: '',
        lastContent: '',
        lastSendTime: new Date().getTime(),
        unreadCount: 0,
        messages: [],
        atMe: false,
        atAll: false,
        stored: false,
      };

      // 使用 chatStore 的方法来获取或创建聊天对象
      this.chatStore.openChat(chatInfo);

      // 通过 chatStore 的方法获取聊天对象
      this.chat = this.chatStore.findChatByTargetId(this.chatIdx);

      // 初始化页面
      this.initChatPage();

      // 激活当前会话
      this.chatStore.activeChat(this.chatIdx);

      this.setupPage();

      // 显示提示信息
      uni.showToast({
        title: "聊天对象不存在或已被删除",
        icon: "none",
        duration: 3000
      });
    },

    loadPrivateChat() {
      // 聊天记录通过 WebSocket 消息获取，不需要 HTTP 接口
      console.log("聊天记录通过 WebSocket 消息获取，无需 HTTP 接口");

      // 创建聊天对象
      const chatInfo = {
        targetId: this.chatIdx,
        type: 'PRIVATE',
        showName: this.userInfo.nickName,
        headImage: this.userInfo.headImageThumb,
        lastContent: '',
        lastSendTime: new Date().getTime(),
        unreadCount: 0,
        messages: [],
        atMe: false,
        atAll: false,
        stored: false,
      };

      // 使用 chatStore 的方法来获取或创建聊天对象
      this.chatStore.openChat(chatInfo);

      // 通过 chatStore 的方法获取聊天对象
      this.chat = this.chatStore.findChatByTargetId(this.chatIdx);

      // 更新好友信息
      this.updateFriendInfo();

      // 初始化页面
      this.initChatPage();

      // 激活当前会话
      this.chatStore.activeChat(this.chatIdx);

      this.setupPage();

      // 如果当前聊天对象没有消息，可以触发 WebSocket 拉取离线消息
      if (!this.chat.messages || this.chat.messages.length === 0) {
        // 触发 WebSocket 重连或拉取离线消息
        uni.$emit('WS_RECONNECTED');
      }
    },

    setupPage() {
      // 设置页面相关配置
      // 复位回执消息
      this.isReceipt = false;
      // 清空引用消息
      this.quoteMessage = null;
      // 监听键盘高度
      this.listenKeyBoard();
      // 计算聊天窗口高度
      this.$nextTick(() => {
        this.windowHeight = uni.getSystemInfoSync().windowHeight;
        this.reCalChatMainHeight();
        // 兼容ios h5:禁止页面滚动
        // #ifdef H5
        this.initHeight = window.innerHeight;
        document.body.addEventListener(
          "touchmove",
          function (e) {
            e.preventDefault();
          }, { passive: false },
        );
        // #endif
      });
    },

    // 确保用户信息已加载
    ensureUserInfoLoaded() {
      return new Promise((resolve, reject) => {
        // 检查用户信息是否已加载
        if (this.userStore.userInfo && this.userStore.userInfo.id) {
          console.log("用户信息已加载:", this.userStore.userInfo);
          resolve();
          return;
        }

        console.log("开始加载用户信息...");

        // 使用 userStore 的 loadUser 方法获取用户信息
        this.userStore.loadUser().then(() => {
          console.log("用户信息加载成功:", this.userStore.userInfo);
          resolve();
        }).catch((err) => {
          console.error("用户信息加载失败:", err);
          reject(err);
        });
      });
    },

    // 确保聊天store已初始化
    ensureChatStoreInitialized() {
      return new Promise((resolve, reject) => {
        // 检查聊天store是否已初始化
        if (this.chatStore.chats.length > 0 || !this.chatStore.isLoading()) {
          console.log("聊天store已初始化");
          resolve();
          return;
        }

        console.log("等待聊天store初始化...");

        // 等待聊天store初始化完成
        const checkInterval = setInterval(() => {
          if (!this.chatStore.isLoading()) {
            clearInterval(checkInterval);
            console.log("聊天store初始化完成");
            resolve();
          }
        }, 100);

        // 设置超时
        setTimeout(() => {
          clearInterval(checkInterval);
          reject(new Error("聊天store初始化超时"));
        }, 10000);
      });
    },

    // 等待WebSocket数据获取完成
    waitForWebSocketData(options) {
      return new Promise((resolve, reject) => {
        console.log("开始等待WebSocket数据获取完成...");

        // 检查是否已经有对应的聊天数据
        const checkExistingData = () => {
          let existingChat = this.chatStore.chats[options.chatIdx];
          if (!existingChat && options.targetId) {
            existingChat = this.chatStore.findChatByTargetId(options.targetId);
          }
          if (!existingChat && options.chatIdx) {
            existingChat = this.chatStore.findChatByTargetId(options.chatIdx);
          }

          // 如果找到了聊天数据，直接返回
          if (existingChat) {
            console.log("找到现有聊天数据，无需等待WebSocket");
            resolve();
            return true;
          }
          return false;
        };

        // 先检查是否已有数据
        if (checkExistingData()) {
          return;
        }

        // 等待WebSocket数据获取完成
        const checkInterval = setInterval(() => {
          // 检查是否还在加载中
          if (!this.chatStore.isLoading()) {
            clearInterval(checkInterval);
            console.log("WebSocket数据获取完成");

            // 再次检查是否有数据
            if (checkExistingData()) {
              return;
            }

            // 如果仍然没有数据，也认为获取完成（可能是新用户或空聊天）
            console.log("WebSocket数据获取完成，但未找到对应聊天数据");
            resolve();
          }
        }, 200);

        // 设置超时时间（15秒）
        setTimeout(() => {
          clearInterval(checkInterval);
          console.warn("等待WebSocket数据超时，继续执行");
          resolve(); // 超时后也继续执行，避免页面卡死
        }, 15000);
      });
    },

    // 加载聊天记录
    loadChatHistory(targetId, chatType) {
      console.log("开始加载聊天记录，targetId:", targetId, "chatType:", chatType);

      // 聊天记录通过 WebSocket 消息获取，不需要 HTTP 接口
      // 直接使用现有的聊天对象，如果没有消息则等待 WebSocket 消息
      console.log("聊天记录通过 WebSocket 消息获取，无需 HTTP 接口");

      // 如果当前聊天对象没有消息，可以触发 WebSocket 拉取离线消息
      if (!this.chat.messages || this.chat.messages.length === 0) {
        // 触发 WebSocket 重连或拉取离线消息
        uni.$emit('WS_RECONNECTED');
      }
    },

    // 更新聊天对象并添加聊天记录，然后使用 openChat 方法
    updateChatWithHistoryAndOpenChat(chatData, chatType) {
      // 聊天记录通过 WebSocket 消息获取，不需要手动更新
      console.log("聊天记录通过 WebSocket 消息获取，无需手动更新");

      // 确保 this.chat 引用 store 中的最新对象
      this.chat = this.chatStore.findChatByTargetId(this.chat.targetId);

      // 重新初始化显示范围
      this.resetShowMessages();

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },

    // 加载聊天记录并使用 openChat 方法（专门用于压缩数据方式）
    loadChatHistoryAndOpenChat(targetId, chatType) {
      console.log("开始加载聊天记录并使用 openChat，targetId:", targetId, "chatType:", chatType);

      // 聊天记录通过 WebSocket 消息获取，不需要 HTTP 接口
      console.log("聊天记录通过 WebSocket 消息获取，无需 HTTP 接口");

      // 初始化页面
      this.initChatPage();
      // 激活当前会话
      this.chatStore.activeChat(targetId);
      this.setupPage();

      // 如果当前聊天对象没有消息，可以触发 WebSocket 拉取离线消息
      if (!this.chat.messages || this.chat.messages.length === 0) {
        // 触发 WebSocket 重连或拉取离线消息
        uni.$emit('WS_RECONNECTED');
      }
    },
  },
  computed: {
    mine() {
      return this.userStore.userInfo;
    },
    isFriend() {
      return this.friendStore.isFriend(this.userInfo.id);
    },
    friend() {
      return this.friendStore.findFriend(this.userInfo.id);
    },
    group() {
      return this.groupStore.findGroup(this.groupId);
    },
    title() {
      if (!this.chat) {
        return "";
      }
      return this.chat.showName;
    },
    messageAction() {
      if (!this.chat) return "";
      return `/message/private/send`;
    },
    messageSize() {
      if (!this.chat || !this.chat.messages) {
        return 0;
      }
      return this.chat.messages.length;
    },
    showMessages() {
      if (!this.chat || !this.chat.messages) {
        return [];
      }
      if (this.showMaxIdx > 0) {
        return this.chat.messages.slice(this.showMinIdx, this.showMaxIdx);
      } else {
        return this.chat.messages.slice(this.showMinIdx);
      }
    },
    unreadCount() {
      if (!this.chat || !this.chat.unreadCount) {
        return 0;
      }
      return this.chat.unreadCount;
    },
    isBanned() {
      return (
        (this.chat && this.chat.type == "PRIVATE" && this.userInfo.isBanned) ||
        (this.chat && this.chat.type == "GROUP" && this.group.isBanned)
      );
    },
    isOwner() {
      return this.group.ownerId == this.mine.id;
    },
    isMuted() {
      return this.chat && this.chat.type == "GROUP" && this.group.isMuted && !this.isOwner;
    },
    atUserItems() {
      let atUsers = [];
      this.atUserIds.forEach((id) => {
        if (id == -1) {
          atUsers.push({
            id: -1,
            showNickName: "全体成员",
          });
          return;
        }
        let member = this.groupMembers.find((m) => m.userId == id);
        if (member) {
          atUsers.push(member);
        }
      });
      return atUsers;
    },
    quoteMessageText() {
      if (!this.quoteMessage) return "";
      const showName = this.showName(this.quoteMessage);
      let content = this.quoteMessage.content;
      switch (this.quoteMessage.type) {
        case this.$enums.MESSAGE_TYPE.IMAGE:
          content = "[图片]";
          break;
        case this.$enums.MESSAGE_TYPE.VIDEO:
          content = "[视频]";
          break;
        case this.$enums.MESSAGE_TYPE.FILE:
          content = "[文件] " + JSON.parse(this.quoteMessage.content).name;
          break;
        case this.$enums.MESSAGE_TYPE.AUDIO:
          content =
            "[语音] " + JSON.parse(this.quoteMessage.content).duration + '"';
          break;
      }
      return showName + ": " + content;
    },
  },
  watch: {
    messageSize: function (newSize, oldSize) {
      // 接收到消息时滚动到底部
      if (newSize > oldSize) {
        let pages = getCurrentPages();
        let curPage = pages[pages.length - 1].route;
        if (curPage == "pages/chat/chat-box") {
          // 收到普通消息,则滚动至底部
          let lastMessage = this.chat.messages[newSize - 1];
          if (oldSize == 0 || this.$msgType.isNormal(lastMessage.type)) {
            this.scrollToBottom();
          }
        } else {
          this.needScrollToBottom = true;
        }
      }
    },
    unreadCount: {
      handler(newCount, oldCount) {
        if (newCount > 0) {
          // 消息已读
          this.readedMessage();
        }
      },
    },
    'chatStore.curChats': {
      handler(newVal) {
        // 如果当前聊天对象存在，尝试从store中同步更新
        if (newVal && this.chat && this.chat.targetId) {
          // 通过targetId查找对应的聊天
          const foundChat = newVal.find(chat => chat.targetId == this.chat.targetId);
          if (foundChat && foundChat !== this.chat) {
            console.log('同步更新聊天对象:', foundChat);
            this.chat = foundChat;
          }
        }
        // 只有在chat对象不存在时才尝试从store中查找
        else if (newVal && this.chatIdx && (!this.chat || !this.chat.targetId)) {
          // 通过targetId查找对应的聊天
          const foundChat = newVal.find(chat => chat.targetId == this.chatIdx);
          if (foundChat) {
            this.chat = foundChat;
            // 避免重复初始化
            if (!this.chat.messages) {
              this.initChatPage();
            }
          }
        }
      },
      deep: true
    }
  },
  onUnload() {
    this.unListenKeyboard();
    // 移除WebSocket重连监听
    uni.$off("WS_RECONNECTED", this.handleWebSocketReconnect);
  },
  onShow() {
    if (this.needScrollToBottom) {
      // 页面滚到底部
      this.scrollToBottom();
      this.needScrollToBottom = false;
    }
  },
};
</script>

<style lang="scss">
.chat-box {
  $icon-color: rgba(0, 0, 0, 0.88);
  position: relative;
  background-color: #fafafa;

  .header {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 60rpx;
    padding: 5px;
    background-color: #fafafa;
    line-height: 50px;
    font-size: $im-font-size-large;
    box-shadow: $im-box-shadow-lighter;
    z-index: 1;

    .btn-side {
      position: absolute;
      line-height: 60rpx;
      cursor: pointer;

      &.right {
        right: 30rpx;
      }
    }
  }

  .chat-main-box {
    // #ifdef H5
    top: $im-nav-bar-height;
    // #endif
    // #ifndef H5
    top: calc($im-nav-bar-height + var(--status-bar-height));
    // #endif
    position: fixed;
    width: 100%;
    display: flex;
    flex-direction: column;
    z-index: 2;

    .chat-msg {
      flex: 1;
      padding: 0;
      overflow: hidden;
      position: relative;
      background-color: white;

      .scroll-box {
        height: 100%;
      }
    }

    .chat-at-bar {
      display: flex;
      align-items: center;
      padding: 0 10rpx;

      .icon-at {
        font-size: $im-font-size-larger;
        color: $im-color-primary;
        font-weight: bold;
      }

      .chat-at-scroll-box {
        flex: 1;
        width: 80%;

        .chat-at-items {
          display: flex;
          align-items: center;
          height: 70rpx;

          .chat-at-item {
            padding: 0 3rpx;
          }
        }
      }
    }

    .send-bar {
      display: flex;
      align-items: center;
      padding: 10rpx;
      border-top: $im-border solid 1px;
      background-color: $im-bg;
      min-height: 80rpx;
      margin-bottom: 14rpx;

      .iconfont {
        font-size: 60rpx;
        margin: 0 10rpx;
        color: $icon-color;
      }

      .chat-record {
        flex: 1;
      }

      .send-text {
        flex: 1;
        overflow: auto;
        padding: 14rpx 20rpx;
        background-color: #fff;
        border-radius: 8rpx;
        font-size: $im-font-size;
        box-sizing: border-box;
        margin: 0 10rpx;
        position: relative;

        .send-text-area {
          width: 100%;
          height: 100%;
          min-height: 40rpx;
          max-height: 200rpx;
          font-size: 30rpx;
        }

        .quote-message {
          background: #eee;
          padding: 5rpx;
          display: flex;
          align-items: center;
          border-radius: 10rpx;

          .quote-text {
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: $im-font-size-smaller;
            color: $im-text-color-lighter;
          }
        }
      }

      .btn-send {
        margin: 5rpx;
      }
    }
  }

  .chat-tab-bar {
    position: fixed;
    bottom: 0;
    background-color: $im-bg;

    .chat-tools {
      display: flex;
      flex-wrap: wrap;
      align-items: top;
      height: 310px;
      padding: 40rpx;
      box-sizing: border-box;

      .chat-tools-item {
        width: 25%;
        padding: 16rpx;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        align-items: center;

        .tool-icon {
          padding: 26rpx;
          font-size: 54rpx;
          border-radius: 20%;
          background-color: white;
          color: $icon-color;

          &:active {
            background-color: $im-bg-active;
          }
        }

        .tool-name {
          height: 60rpx;
          line-height: 60rpx;
          font-size: 28rpx;
        }
      }
    }

    .chat-emotion {
      height: 310px;
      padding: 20rpx;
      box-sizing: border-box;

      .emotion-item-list {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        align-content: center;

        .emotion-item {
          text-align: center;
          cursor: pointer;
          padding: 5px;
        }
      }
    }
  }
}
</style>